# Setup -------------------------------------------------------------------
rm(list = ls())
source("figure_design.R")

# Data --------------------------------------------------------------------

vdem <- readRDS("vdem_v14_subset.rds")
covariates <- readRDS("covariates_subset.rds")
wvs_evs <- readRDS("ivs_1981-2021_subset.rds")
evs_party <- read.csv("evs_party.csv",encoding = 'UTF-8')
wvs_party <- read.csv("wvs_party.csv",encoding = 'UTF-8')

# Recoding V-Dem ----------------------------------------------------------

vdem_subset <- vdem %>%
  left_join(covariates, by = c("country_name","year")) %>%
  mutate(v2x_regime = case_when(
    v2x_regime == 0 ~ "Closed Autocracy" ,
    v2x_regime == 1 ~ "Electoral Autocracy",
    v2x_regime == 2 ~ "Electoral Democracy",
    v2x_regime == 3 ~ "Liberal Democracy",
    TRUE ~ NA_character_),
    country_name = case_when(country_name == "Czechia" ~ "Czech Republic",
                             country_name == "United Kingdom" ~ "Great Britain",
                             country_name == "Taiwan" ~ "Taiwan ROC",
                             country_name == "United States of America" ~ "United States",
                             TRUE ~ country_name)) %>%
  rename(country = country_name,
        regime = v2x_regime,
        democracy_score = v2x_polyarchy) %>%
  select(country,year,regime,democracy_score,consumer_price_index,unemployment,gdp,gdp_growth)

# Party data --------------------------------------------------------------

evs_party %>% mutate(gov_status_evs = case_when(head_of_government == 1 |
                                                  minister_government == 1 |
                                                  government_support == 1 ~"Government",
                                                head_of_government == 0 &
                                                  minister_government == 0 &
                                                  government_support == 0 ~"Opposition",
                                                TRUE ~ NA_character_)) %>%
  select(party,gov_status_evs) ->
  evs_party

wvs_party %>% mutate(gov_status_wvs = case_when(head_of_government == 1 |
                                                  minister_government == 1 |
                                                  government_support == 1 ~"Government",
                                                head_of_government == 0 &
                                                  minister_government == 0 &
                                                  government_support == 0 ~"Opposition",
                                                TRUE ~ NA_character_)) %>%
  select(party,gov_status_wvs) ->
  wvs_party

# Survey data -------------------------------------------------------------

# E265_01	How often in country's elections: Votes are counted fairly
# E265_02	How often in country's elections: Opposition candidates are prevented from running
# E265_03	How often in country's elections: TV news favors the governing party
# E265_04	How often in country's elections: Voters are bribed
# E265_05	How often in country's elections: Journalists provide fair coverage of elections
# E265_06	How often in country's elections: Election officials are fair
# E265_07	How often in country's elections: Rich people buy elections
# E265_08	How often in country's elections: Voters are threatened with  violence at the polls
# E265_09	How often in country's elections: Voters are offered a genuine choice in the elections
# S020	Year survey
# E069_11 Confidence Government

wvs_evs %>% mutate(study = to_factor(S001),
                   year = remove_labels(S020),
                   country = remove_labels(to_factor(COW_NUM)),
                   country = str_sub(country,2)) %>%
  filter(!(country == " Serbia" & study == "WVS")) %>% # remove double sample
  filter(!(country == " Germany" & study == "WVS")) %>% # remove double sample
  filter(year > 2009) %>%
  select(year,country,A165,E033,S012,E265_01:E265_09,S017,X001,X003,E023,X025A,X046,E179WVS,E181A) %>%
  left_join(vdem_subset, by=c("country","year")) %>%
  filter(regime %in% c("Electoral Democracy","Liberal Democracy","Electoral Autocracy")) %>% 
  mutate(EI_01 = 5-remove_labels(E265_01),
         EI_02 = 5-remove_labels(E265_02),
         EI_03 = 5-remove_labels(E265_03),
         EI_04 = 5-remove_labels(E265_04),
         EI_05 = 5-remove_labels(E265_05),
         EI_06 = 5-remove_labels(E265_06),
         EI_07 = 5-remove_labels(E265_07),
         EI_08 = 5-remove_labels(E265_08),
         EI_09 = 5-remove_labels(E265_09),
         party_WVS = paste(to_factor(E179WVS),year),
         party_WVS = as.factor(ifelse(!is.na(E179WVS),party_WVS,NA)),
         party_EVS = paste(to_factor(E181A),year),
         party_EVS = as.factor(ifelse(!is.na(E181A),party_EVS,NA)),
         weight = remove_labels(S017),
         gender = as.numeric(remove_labels(X001)),
         age = remove_labels(X003),
         interest_politics = 5-remove_labels(E023),
         education = remove_labels(X025A),
         soc_status = 5 - remove_labels(X046),
         interpersonal_trust = remove_labels(A165),
         left_right_placement = remove_labels(E033),
         wave = ifelse(year<2015,"Pre 2015","Post 2015"),
         date = remove_labels(S012)) %>%
  mutate_at(vars(c(interest_politics,left_right_placement,
                   age,consumer_price_index,unemployment,gdp,gdp_growth)), ~ (. - mean(.,na.rm=T)) / (2 * sd(.,na.rm=T))) %>% # standardize covariates
  filter_at(vars(EI_01:EI_09), any_vars(!is.na(.))) %>%
  mutate(EI_mean = (EI_01+(5-EI_02)+(5-EI_03)+(5-EI_04)+EI_05+EI_06+(5-EI_07)+(5-EI_08)+EI_09)/9,
         interpersonal_trust = case_when(interpersonal_trust == 1 ~ 1,
                                         interpersonal_trust == 2 ~ 0,
                                         TRUE ~ NA_real_),
         gender = case_when(gender == 2 ~ 1,
                            gender == 1 ~ 0,
                            TRUE ~ NA_real_)) %>% 
  left_join(wvs_party,by=c("party_WVS" = "party")) %>%
  left_join(evs_party,by=c("party_EVS" = "party")) %>%
  mutate(gov_status = case_when(gov_status_wvs == "Government" | gov_status_evs == "Government" ~"Government",
                                gov_status_wvs == "Opposition" | gov_status_evs == "Opposition" ~"Opposition"),
         gov_status_na = case_when(gov_status_wvs == "Government" | gov_status_evs == "Government" ~"Government",
                                   TRUE ~ "Opposition"),
         regime = factor(regime, levels = c("Liberal Democracy","Electoral Democracy","Electoral Autocracy"))) %>%
  select(-gov_status_wvs,-gov_status_evs) ->
  merged_data

# Hierarchical IRT --------------------------------------------------------

data.irt <- merged_data
country <- as.vector(data.irt$country)
wave <- as.vector(data.irt$wave)
items <- dplyr::select(data.irt,EI_01:EI_09)

country_matrix <- model.matrix( ~ country + wave, data.irt)
elections_hirt <- hgrm(y = items,x = country_matrix)

irt_output <- summary(elections_hirt)
irt_fit <- irt_output[["model"]]
irt_coefs <- irt_output[["item_coefs"]]
irt_intercept <-  irt_output[["mean_coefs"]]

election_scores_hirt <- latent_scores(elections_hirt,3)
merged_data$election_scores_hirt <- election_scores_hirt$post_mean

saveRDS(merged_data,file="ivs_recoded.rds")
merged_data <- readRDS("ivs_recoded.rds")

# Figure 1a ---------------------------------------------------------------

merged_data  %>% filter(year>2015)  %>%
  filter(!is.na(gov_status)) %>%
  as_survey(weights = c(weight)) %>%
  group_by(year,country,gov_status)  %>%  
  summarise(mean=survey_mean(election_scores_hirt, na.rm=T, vartype=c("ci"))) %>% 
  select(country,gov_status,mean) %>%
  left_join(vdem_subset, by=c("country","year")) %>% 
  filter(regime=="Electoral Democracy"|regime=="Liberal Democracy"|regime=="Electoral Autocracy") ->
  mean_data

plot_comparison <- ggplot(mean_data, aes(x = democracy_score, y = mean, color = gov_status, group = country)) +
  geom_line(color = "grey") +
  geom_point(aes(shape = gov_status), size = 2) +  # Different shapes for gov_status
  xlab("Polyarchy") +
  ylab("Perceived Electoral Integrity") +
  geom_smooth(aes(fill = gov_status, group = gov_status, linetype = gov_status)) +
  scale_color_manual(values = plot_colors) +
  scale_fill_manual(values = plot_colors)

plot_comparison

ggsave(plot_comparison, filename = "fig_1a.pdf", device = cairo_pdf, 
       width = 6, height = 5, units = "in")

# Figure 1b ---------------------------------------------------------------

merged_data  %>% filter(year>2015)  %>%
  filter(!is.na(gov_status)) %>%
  as_survey(weights = c(weight)) %>%
  group_by(year,country,gov_status)  %>%  
  summarise(mean=survey_mean(election_scores_hirt,na.rm=T,vartype=c("ci"))) %>% 
  select(country,gov_status,mean)  %>%
  spread(key="gov_status",-year) %>%
  left_join(vdem_subset, by=c("country","year")) %>% 
  filter(regime=="Electoral Democracy"|regime=="Liberal Democracy"|regime=="Electoral Autocracy") %>%
  mutate(differential = Government - Opposition) ->
  mean_data

plot_comparison <- ggplot(mean_data) +
  geom_hline(yintercept = 0, linetype = "dashed", color = "grey") +
  geom_segment(aes(x=democracy_score, xend=democracy_score, y=differential, yend=0), color = "grey") +
  geom_point( aes(x=democracy_score, y=differential), color="black",size=2) +
  xlab("Polyarchy") +
  ylab("Perceived Electoral Integrity Differential") +
  geom_smooth(aes(x = democracy_score, y = differential), colour = "black")

plot_comparison

ggsave(plot_comparison, filename = "fig_1b.pdf", device = cairo_pdf, 
       width = 6, height = 5, units = "in")

# Table 2 -----------------------------------------------------------------

m1 <- lmer(election_scores_hirt ~ gov_status + regime + (1|country/wave), weights = weight, data = merged_data)

m2 <- lmer(election_scores_hirt ~ gov_status + regime + gov_status*regime +  (1|country/wave), weights = weight, data = merged_data)

m3 <- lmer(election_scores_hirt ~ gov_status + regime + gov_status*regime + 
                                  interest_politics + interpersonal_trust + left_right_placement + gender + age + 
                                  consumer_price_index + unemployment + gdp + gdp_growth + 
                                  (1|country/wave), weights = weight, data = merged_data)

texreg(list(m1,m2,m3),
       file = "tab_2.tex",
       include.ci = F,
       digits = 3,
       custom.coef.map = list(
         "gov_statusOpposition" = "Opposition (vs. government)",
         "regimeElectoral Democracy" = "Electoral democracy (vs. liberal democracy)",
         "regimeElectoral Autocracy" = "Electoral authoritarianism (vs. liberal democracy)",
         "gov_statusOpposition:regimeElectoral Democracy" = "Opposition $\\times$ electoral democracy",
         "gov_statusOpposition:regimeElectoral Autocracy" = "Opposition $\\times$ electoral authoritarianism",
         "interest_politics" = "Interest in politics",
         "interpersonal_trust" = "Interpersonal trust",
         "left_right_placement" = "Left-right placement",
         "gender" = "Female (vs. male)",
         "age" = "Age",
         "unemployment" = "Unemployment",
         "gdp" = "log(GDP)",
         "gdp_growth" = "GDP growth",
         "consumer_price_index" = "Consumer price index"
       ),
       groups = list("Individual" = 6:10,"Country" = 11:14),
       booktabs = T,
       use.packages=F,	
       custom.gof.rows = list("Country Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$"),
                              "Country/Wave Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$")),
       include.rmse = FALSE,
       caption = "OLS regression of perceived electoral integrity scores with survey weights. Data source: \textit{WVS/EVS 2017-2021}.",
       label = "tab1")

# Figure 2 ----------------------------------------------------------------

m3_me <- ggeffects::ggpredict(m3,c("regime","gov_status")) %>%
         mutate(x = factor(x, levels = c("Electoral Autocracy","Electoral Democracy","Liberal Democracy")))

plot_me <- ggplot(m3_me,aes(y=predicted,x=x,shape=group, color=group)) +
  geom_errorbar(aes(ymin=conf.low, ymax=conf.high), width=0.03,position=position_dodge(0.3)) + 
  geom_point(position = position_dodge(width = 0.3)) +
  labs(x = "", y="Predicted Values") +
  theme(legend.position="top") + 
  theme(legend.title=element_blank(),
        axis.text.x = element_text(angle = 45, hjust = 1)) + 
  scale_color_manual(values = plot_colors)


ggsave(plot_me, filename = "fig_2.pdf", device = cairo_pdf, 
       width = 3, height = 4, units = "in")

range <- max(merged_data$election_scores_hirt) - min(merged_data$election_scores_hirt)

# percent decrease electoral autocracy
round(((m3_me$predicted[m3_me$x=="Electoral Autocracy"&m3_me$group=="Opposition"] -
    m3_me$predicted[m3_me$x=="Electoral Autocracy"&m3_me$group=="Government"]) /
  range),3)

# percent decrease electoral democracy
round(((m3_me$predicted[m3_me$x=="Electoral Democracy"&m3_me$group=="Opposition"] -
    m3_me$predicted[m3_me$x=="Electoral Democracy"&m3_me$group=="Government"]) /
  range),3)

# percent decrease liberal democracy
round(((m3_me$predicted[m3_me$x=="Liberal Democracy"&m3_me$group=="Opposition"] -
    m3_me$predicted[m3_me$x=="Liberal Democracy"&m3_me$group=="Government"]) /
  range),3)

# APPENDIX A --------------------------------------------------------------

# Table A.3 ---------------------------------------------------------------

merged_data %>% select(EI_01,EI_02,EI_03,EI_04,EI_05,EI_06,
                    EI_07,EI_08,EI_09,
                    gov_status,democracy_score,
                    interest_politics,interpersonal_trust,left_right_placement,gender,age,
                    consumer_price_index,unemployment,gdp,gdp_growth) %>%
  mutate(gov_status = case_when(gov_status=="Government"~1,
                                gov_status=="Opposition"~0,
                                TRUE ~ NaN)) %>%
  as.data.frame() ->
  desciptives

stargazer(desciptives,type="latex",
          out = "tab_a3.tex",
          covariate.labels = c("Electoral Integrity 1",
                               "Electoral Integrity 2",
                               "Electoral Integrity 3",
                               "Electoral Integrity 4",
                               "Electoral Integrity 5",
                               "Electoral Integrity 6",
                               "Electoral Integrity 7",
                               "Electoral Integrity 8",
                               "Electoral Integrity 9",
                               "Government supporter",
                               "Polyarchy (V-Dem)",
                               "Interest in politics",
                               "Interpersonal trust",
                               "Left-right placement",
                               "Gender",
                               "Age",
                               "Consumer price index",
                               "Unemployment",
                               "Log(GDP)",
                               "GDP growth"))


# Table A.4 ---------------------------------------------------------------

estimates <- rbind(irt_coefs,irt_intercept) %>%
  mutate(Parameter = rownames(.)) %>%
  select(Parameter,Estimate,Std_Error,z_value,p_value)

estimates %>% add_row(Parameter = c("Log Likelihood","AIC","BIC"),
                      Estimate = c(irt_fit[["log_Lik"]],irt_fit[["AIC"]],irt_fit[["BIC"]])) ->
  irt_table

write.csv(irt_table,file="tab_a4.csv",row.names = F)

# Table A.5 ---------------------------------------------------------------

m1 <- lmer(EI_mean ~ gov_status + regime + (1|country/wave), weights = weight, data = merged_data)

m2 <- lmer(EI_mean ~ gov_status + regime + gov_status*regime +  (1|country/wave), weights = weight, data = merged_data)

m3 <- lmer(EI_mean ~ gov_status + regime + gov_status*regime + 
             interest_politics + interpersonal_trust + left_right_placement + gender + age + 
             consumer_price_index + unemployment + gdp + gdp_growth + 
             (1|country/wave), weights = weight, data = merged_data)

texreg(list(m1,m2,m3),
       file = "tab_a5.tex",
       include.ci = F,
       digits = 3,
       custom.coef.map = list(
         "gov_statusOpposition" = "Opposition (vs. government)",
         "regimeElectoral Democracy" = "Electoral democracy (vs. liberal democracy)",
         "regimeElectoral Autocracy" = "Electoral authoritarianism (vs. liberal democracy)",
         "gov_statusOpposition:regimeElectoral Democracy" = "Opposition $\\times$ electoral democracy",
         "gov_statusOpposition:regimeElectoral Autocracy" = "Opposition $\\times$ electoral authoritarianism",
         "interest_politics" = "Interest in politics",
         "interpersonal_trust" = "Interpersonal trust",
         "left_right_placement" = "Left-right placement",
         "gender" = "Female (vs. male)",
         "age" = "Age",
         "unemployment" = "Unemployment",
         "gdp" = "log(GDP)",
         "gdp_growth" = "GDP growth",
         "consumer_price_index" = "Consumer price index"
       ),
       groups = list("Individual controls" = 6:10,"Country controls" = 11:14),
       booktabs = T,
       use.packages=F,	
       custom.gof.rows = list("Country Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$"),
                              "Country/Wave Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$")),
       include.rmse = FALSE,
       caption = "OLS regression of perceived electoral integrity scores (mean) with survey weights.")


# Figure A.1 --------------------------------------------------------------

m3_me <- ggeffects::ggpredict(m3,c("regime","gov_status")) %>%
  mutate(x = factor(x, levels = c("Electoral Autocracy","Electoral Democracy","Liberal Democracy")))

plot_me <- ggplot(m3_me,aes(y=predicted,x=x,shape=group, color=group)) +
  geom_errorbar(aes(ymin=conf.low, ymax=conf.high), width=0.03,position=position_dodge(0.3)) + 
  geom_point(position = position_dodge(width = 0.3)) +
  labs(x = "", y="Predicted Values") +
  theme(legend.position="top") + 
  theme(legend.title=element_blank(),
        axis.text.x = element_text(angle = 45, hjust = 1)) + 
  scale_color_manual(values = plot_colors)


ggsave(plot_me, filename = "fig_a1.pdf", device = cairo_pdf, 
       width = 3, height = 4, units = "in")


# Table A.7 ---------------------------------------------------------------

item_names <- colnames(items)
separate_items <- list()  

for (y in item_names) {
  output <- lmer(paste(y,  '~','gov_status + regime + gov_status*regime + 
             interest_politics + interpersonal_trust + left_right_placement + gender + age + 
             consumer_price_index + unemployment + gdp + gdp_growth + (1|country/wave)'),
                 weights = weight, data = merged_data)
  separate_items[[y]] <- output
}

texreg(separate_items,
       file = "tab_a7.tex",
       include.ci = F,
       digits = 3,
       custom.coef.map = list(
         "gov_statusOpposition" = "Opposition (vs. government)",
         "regimeElectoral Democracy" = "Electoral democracy (vs. liberal democracy)",
         "regimeElectoral Autocracy" = "Electoral authoritarianism (vs. liberal democracy)",
         "gov_statusOpposition:regimeElectoral Democracy" = "Opposition $\\times$ electoral democracy",
         "gov_statusOpposition:regimeElectoral Autocracy" = "Opposition $\\times$ electoral authoritarianism"
       ),
       booktabs = T,
       use.packages=F,	
       custom.gof.rows = list("Individual controls" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$"),
                              "Country controls" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$"),
                              "Country Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$"),
                              "Country/Wave Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$","$\\checkmark$")),
       include.rmse = FALSE,
       caption = "OLS regression of perceived electoral integrity by item with survey weights.")


# Figure A.2 --------------------------------------------------------------

marginal_effects <- list()  

for (y in item_names) {
  output <- ggeffects::ggpredict(separate_items[[y]],c("regime","gov_status")) %>% as.data.frame()
  output %>% mutate(item = paste(y)) -> output
  marginal_effects[[y]] <- output
}

marginal_effects %>% bind_rows() %>% 
  mutate(x = factor(x, levels = c("Electoral Autocracy","Electoral Democracy","Liberal Democracy"))) ->
           marginal_effects_joint

plot_me_separate <- ggplot(marginal_effects_joint,aes(y=predicted,x=x,shape=group, color=group)) +
  geom_errorbar(aes(ymin=conf.low, ymax=conf.high), width=0.03,position=position_dodge(0.3)) + 
  geom_point(position = position_dodge(width = 0.3)) +
  labs(x="", y="Predicted Values") +
  theme(legend.title=element_blank()) + 
  facet_wrap(~item,ncol = 2,scales ="free_y") + 
  theme(axis.text.x = element_text(size = 6, angle = 45,hjust = 1, vjust = 1)) + 
  scale_color_manual(values = plot_colors)

ggsave(plot_me_separate, filename = "fig_a2.pdf", device = cairo_pdf, 
       width = 7, height = 10, units = "in")


# Figure A.3 --------------------------------------------------------------

merged_data %>% select(country,year,election_scores_hirt,democracy_score,gov_status,interest_politics,interpersonal_trust,
                       left_right_placement,gender,age,consumer_price_index,unemployment,gdp,gdp_growth) %>% 
  drop_na(election_scores_hirt,democracy_score,gov_status,interest_politics,interpersonal_trust,
          left_right_placement,gender,age,consumer_price_index,unemployment,gdp,gdp_growth) %>% 
  mutate(gov_status = case_when(gov_status == "Opposition" ~ 1,
                                gov_status == "Government" ~ 0)) %>% 
  as.data.frame() -> 
  binning_data

binning <- interflex(Y = "election_scores_hirt",
                     D = "gov_status", 
                     X = "democracy_score", 
                     data = binning_data,
                     estimator = "binning",
                     na.rm = TRUE,
                     Ylabel = "Electoral integrity",
                     Dlabel = "Opposition support",
                     Xlabel = "Polyarchy",
                     FE = c("country", "year"), 
                     Z = c("interest_politics","interpersonal_trust","left_right_placement",
                           "gender","age","consumer_price_index","unemployment","gdp","gdp_growth"),
                     theme.bw = T)

ggsave(plot(binning), filename = "fig_a3.pdf", device = cairo_pdf, 
       width = 5, height = 7, units = "in")

# Table A.8 ---------------------------------------------------------------

m1 <- lmer(election_scores_hirt ~ gov_status_na + regime + (1|country/wave), weights = weight, data = merged_data)

m2 <- lmer(election_scores_hirt ~ gov_status_na + regime + gov_status_na*regime +  (1|country/wave), weights = weight, data = merged_data)

m3 <- lmer(election_scores_hirt ~ gov_status_na + regime + gov_status_na*regime + 
             interest_politics + interpersonal_trust + left_right_placement + gender + age + 
             consumer_price_index + unemployment + gdp + gdp_growth + 
             (1|country/wave), weights = weight, data = merged_data)

texreg(list(m1,m2,m3),
       file = "tab_a8.tex",
       include.ci = F,
       digits = 3,
       custom.coef.map = list(
         "gov_status_naOpposition" = "Opposition (vs. government)",
         "regimeElectoral Democracy" = "Electoral democracy (vs. liberal democracy)",
         "regimeElectoral Autocracy" = "Electoral authoritarianism (vs. liberal democracy)",
         "gov_status_naOpposition:regimeElectoral Democracy" = "Opposition $\\times$ electoral democracy",
         "gov_status_naOpposition:regimeElectoral Autocracy" = "Opposition $\\times$ electoral authoritarianism",
         "interest_politics" = "Interest in politics",
         "interpersonal_trust" = "Interpersonal trust",
         "left_right_placement" = "Left-right placement",
         "gender" = "Female (vs. male)",
         "age" = "Age",
         "unemployment" = "Unemployment",
         "gdp" = "log(GDP)",
         "gdp_growth" = "GDP growth",
         "consumer_price_index" = "Consumer price index"
       ),
       groups = list("Individual controls" = 6:10,"Country controls" = 11:14),
       booktabs = T,
       use.packages=F,	
       custom.gof.rows = list("Country Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$"),
                              "Country/Wave Random Effects" = c("$\\checkmark$","$\\checkmark$","$\\checkmark$")),
       include.rmse = FALSE,
       caption = "OLS regression of perceived electoral integrity scores with survey weights.")


# Figure A.4 --------------------------------------------------------------

m3_me <- ggeffects::ggpredict(m3,c("regime","gov_status_na")) %>%
  mutate(x = factor(x, levels = c("Electoral Autocracy","Electoral Democracy","Liberal Democracy")))

plot_me <- ggplot(m3_me,aes(y=predicted,x=x,shape=group, color=group)) +
  geom_errorbar(aes(ymin=conf.low, ymax=conf.high), width=0.03,position=position_dodge(0.3)) + 
  geom_point(position = position_dodge(width = 0.3)) +
  labs(x = "", y="Predicted Values") +
  theme(legend.position="top") + 
  theme(legend.title=element_blank(),
        axis.text.x = element_text(angle = 45, hjust = 1)) + 
  scale_color_manual(values = plot_colors)

ggsave(plot_me, filename = "fig_a4.pdf", device = cairo_pdf, 
       width = 3, height = 4, units = "in")